<template>
  <Card>
    <Row type="flex"
         align="top"
         justify="space-between">
      <Form ref="formSearch"
            class="sellPending"
            inline>
        <FormItem label="场馆"
                  v-if="!userInfo.storeId">
          <Select v-model="formSearch.storeId"
                  style="width:150px"
                  clearable>
            <Option v-for="(item, index) in storeIdList"
                    :key="index"
                    :value="item.id">{{item.storeName}}</Option>
          </Select>
        </FormItem>
        <FormItem label="顾问"
                  prop="sendCardUser">
          <Select v-model="formSearch.action"
                  style="width:100px"
                  clearable>
            <Option v-for="(item, index) in staffList"
                    :key="index"
                    :value="item.nickname">{{item.nickname}}</Option>
          </Select>
        </FormItem>

        <FormItem label="来源">
          <Select v-model="formSearch.resource"
                  style="width:100px"
                  clearable>
            <Option v-for="(item, index) in source"
                    :key="index"
                    :value="item">{{item}}</Option>
          </Select>
        </FormItem>
        <FormItem label="手机/姓名">
          <Row>
            <Col span="18">
            <Input clearable
                   placeholder="输入手机/姓名搜索"
                   class="search-input"
                   v-model="formSearch.realname" />
            </Col>
            <Col span="4"
                 offset="1">
            <Button class="search-btn"
                    @click="memberList"
                    type="primary">
              <Icon type="search" />搜索</Button>
            </Col>
          </Row>

        </FormItem>
      </Form>
      <Button class="margin-b-20"
              icon="md-add"
              type="primary"
              @click="addMemberModal = true">添加会员</Button>
    </Row>
    <Table border
           :loading="tableLoading"
           :columns="memberListColumns"
           :data="memberData">
    </Table>
    <Row type="flex"
         class="margin-t-20">
      <Page :total="pageTotal"
            @on-change="changePage" />
    </Row>
    <br>
    <Button type="primary"
            v-if="!userInfo.storeId"
            size="large"
            @click="exportMember">
      <Icon type="ios-download-outline"></Icon> 导出数据
    </Button>
    <Modal :title="memberType ? '编辑会员' :'添加会员'"
           :loading="loading"
           :mask-closable="false"
           fullscreen
           scrollable
           @on-ok="onMemberSubmit"
           @on-visible-change="onAddMemberVisible"
           v-model="addMemberModal">
      <add-member @addStaffModel="memberList"
                  :storeIdList="storeIdList"
                  ref="addMemberForm"></add-member>
    </Modal>

    <Modal title="会员详情"
           :mask-closable="false"
           fullscreen
           scrollable
           v-model="detailsModal">
      <member-details ref="detailsModal"></member-details>
      <div slot="footer">
        <Button type="error"
                size="large"
                long
                @click="detailsModal = false">关闭</Button>
      </div>
    </Modal>
  </Card>

</template>
<script>
import addMember from './components/add'
import memberDetails from './components/member-details'
import { formatDateTime } from '@/libs/util'
import { mapGetters } from 'vuex'
import { storeAll } from '@/api/setting-shop'
import { cardList } from '@/api/setting-course'
import { staffList } from '@/api/setting-staff'
import { memberList, deleteMember, exportMember } from '@/api/user'
export default {
  components: {
    addMember,
    memberDetails
  },
  data () {
    return {
      phone: '',
      detailsModal: false,
      tableLoading: false,
      // 场馆列表
      storeIdList: [],
      // 店员列表
      staffList: [],
      // 来源列表
      source: ['美团', '口碑', '转介绍', '自来网络', '地推', '其他'],
      memberListColumns: [
        {
          title: '姓名',
          key: 'realname',
          fixed: 'left',
          minWidth: 100
        },
        {
          title: '性别',
          key: 'sex',
          minWidth: 100,
          render: (h, params) => {
            return h(
              'span',
              {},
              params.row.sex ? '男' : '女'
            )
          }
        },
        {
          title: '电话',
          key: 'phone',
          minWidth: 140
        },
        {
          title: '出生日期',
          key: 'birthday',
          minWidth: 140,
          render: (h, params) => {
            return h(
              'span',
              {},
              formatDateTime(params.row.birthday)
            )
          }
        },
        {
          title: '所属场馆',
          key: 'storeId',
          minWidth: 140,
          render: (h, params) => {
            for (let i of this.storeIdList) {
              if (params.row.storeId === i.id) {
                return h(
                  'span',
                  {},
                  i.storeName
                )
              }
            }
          }
        },
        {
          title: '来源',
          key: 'resource',
          minWidth: 100
        },
        {
          title: '操作员',
          key: 'action',
          minWidth: 100
        },
        {
          title: '添加时间',
          key: 'createTime',
          minWidth: 140,
          render: (h, params) => {
            return h('span', {
              style: {
              }
            }, formatDateTime(params.row.createTime))
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 150,
          fixed: 'right',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.detailsModal = true
                    this.$refs.detailsModal.getByPhone(params.row.phone)
                  }
                }
              }, '详情'),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                on: {
                  click: () => {
                    this.deleteMember(params.row.id)
                  }
                }
              }, '删除')
            ])
          }
        }
      ],
      memberData: [],
      pageTotal: 0,
      // 筛选条件
      formSearch: {
        resource: '',
        realname: '',
        storeId: 0,
        size: 10,
        page: 1,
        action: ''
      },
      // 弹框
      memberType: 0,
      loading: true,
      addMemberModal: false
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },
  async created () {
    this.tableLoading = true
    if (this.userInfo.storeId) {
      this.$set(this.formSearch, 'storeId', this.userInfo.storeId)
    }
    await this.storeAll()
    await this.getStaffList()
    await this.memberList()
  },
  methods: {
    storeAll () { // 场馆列表
      return new Promise((resolve, reject) => {
        storeAll().then(res => {
          this.storeIdList = res.data
          resolve(res.data)
        })
      })
    },
    getStaffList () { // 店员列表
      return new Promise((resolve, reject) => {
        staffList({ size: 200, storeId: this.formSearch.storeId }).then(res => {
          this.staffList = res.data.rows
          resolve(res.data.rows)
        })
      })
    },
    cardList () { // 卡列表
      return new Promise((resolve, reject) => {
        cardList({
          name: '',
          type: '',
          varieties: ''
        }).then(res => {
          this.cardNameList = res.data
          res.data.forEach(e => {
            this.cardNameObj['card' + e.id] = e.name
          })
          setTimeout(() => {
            resolve(res.data)
          }, 10)
        })
      })
    },
    memberList () {
      this.tableLoading = true
      this.formSearch.storeId = this.formSearch.storeId || 0
      memberList(this.formSearch).then(res => {
        this.memberData = res.data.records
        this.pageTotal = res.data.total
        this.tableLoading = false
        this.addMemberModal = false
      })
    },
    onMemberSubmit () {
      setTimeout(() => {
        this.loading = false
      }, 300)
      setTimeout(() => {
        this.loading = true
      }, 400)
      this.$refs['addMemberForm'].onMemberSubmit()
    },
    deleteMember (id) {
      this.$Modal.confirm({
        title: '提示',
        content: '确定删除？',
        loading: true,
        okText: '删除',
        onOk: () => {
          deleteMember(id)
            .then(res => {
              this.$Modal.remove()
              this.$Message.success('删除成功')
              this.memberList()
            })
            .catch(() => {
              this.$Modal.remove()
            })
        }
      })
    },
    exportMember () { // 导出数据
      const { action, storeId, resource } = this.formSearch
      exportMember({
        page: 1,
        storeId: storeId,
        size: this.pageTotal,
        action: action,
        resource: resource
      }).then(res => {
        const link = document.createElement('a')
        let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        console.log(res.headers['content-disposition'])
        // link.download = res.headers['content-disposition'].match(/filename=(\S*)/)[1] // 下载后文件名
        link.download = '会员列表.xls'// 下载的文件名
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)

        this.$Message.success('导出成功')
      })
    },
    onAddMemberVisible (visible) {
      // 弹框状态改变 清除默认值
      if (visible) return
      this.$refs['addMemberForm'].resetFields()
    },
    changePage (val) {
      this.formSearch = { ...this.formSearch, page: val }
      this.memberList()
    }
  }
}
</script>
<style lang="less">
.sellPending {
  flex: 1;
  .search-item {
    display: flex;
    margin-bottom: 10px;
    .search-btn {
      margin-left: 20px;
    }
  }
}
.receiverTypeTip {
  text-align: center;
  overflow: hidden;
  &-title {
    margin-bottom: 5px;
  }
  &-img {
    width: 200px;
    overflow: hidden;
    img {
      width: 100%;
      height: auto;
    }
  }
}
.confirmRemberModalRow {
  margin-bottom: 10px;
}
.loading-drop-down {
  display: flex;
  align-items: center;
  padding: 2px 16px;
  background-color: #f2f6fa;
  color: #357ce1;
  border-radius: 2px;
}
</style>
